package com.test.mysqlseq.service;

import com.google.common.base.Strings;
import com.test.mysqlseq.entity.TSysSeq;
import com.test.mysqlseq.entity.TSysSeqExample;
import com.test.mysqlseq.mapper.TSysSeqMapper;
import com.test.utils.SequenceIdGenerator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

@Service
@Transactional
public class SeqServiceImpl implements SeqService {

    @Resource
    private TSysSeqMapper sysSeqMapper;

    @Resource
    private SequenceIdGenerator sequenceIdGenerator;

    @Override
    public Integer[] getSeq(int count) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String seqKey = sdf.format(Calendar.getInstance().getTime());
        Integer[] seqs = new Integer[count];
        for (int i = 0; i < count; i++) {
            int seq = sysSeqMapper.getSeq(seqKey, 1, 3L);
            seqs[i] = seq;
            System.out.println("[Times]" + i + ",[Seq]=" + seq);
        }
        return seqs;
    }

    @Override
    public synchronized Long getSeq() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String seqKey = sdf.format(Calendar.getInstance().getTime());
        Long ret = this.getSeq(seqKey, 1, 3L);
        return ret;
    }

    @Override
    public Long getSeq(String seqKey, int seqType, Long bizId) {
        TSysSeqExample example = new TSysSeqExample();
        example.createCriteria().andSequkeyEqualTo(seqKey).andSequtypeEqualTo(seqType).andBizidEqualTo(bizId);
        List<TSysSeq> seqList = sysSeqMapper.selectByExample(example);
        Long ret = 0L;
        if (seqList == null || seqList.isEmpty()) {
            TSysSeq seq = new TSysSeq();
            seq.setId(sequenceIdGenerator.nextId());
            seq.setSequkey(seqKey);
            seq.setSequtype(seqType);
            seq.setBizid(bizId);
            seq.setSequvalue(1L);
            seq.setStep(1);
            seq.setUpdatetime(Calendar.getInstance().getTime());
            sysSeqMapper.insert(seq);
            ret = 1L;
        } else {
            TSysSeq seq = seqList.get(0);
            ret = seq.getSequvalue() + seq.getStep();
            seq.setSequvalue(ret);
            seq.setUpdatetime(Calendar.getInstance().getTime());
            sysSeqMapper.updateByPrimaryKey(seq);
        }
        return ret;
    }

    @Override
    public synchronized String getOutPatientCode(Long bizId) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String seqKey = sdf.format(Calendar.getInstance().getTime());
        Long ret = this.getSeq(seqKey, 1, bizId);
        return seqKey + Strings.padStart(String.valueOf(ret), 4, '0');
    }
}
